package com.xiaojie.dubbo.server.loadBalance;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: Hash一致性算法
 * 通过ip对集合长度hash取模，从而确定IP一致的，访问的服务器地址也一致
 * @author: xiaojie
 * @date: 2021.08.06
 */
public class HashLoadBalance implements  LoadBalance<String > {
    static int index = 0;
    @Override
    public String  select(List<String> repos) {

        if (repos.size()<=0){
             throw new RuntimeException("repos is null");
        }
        if (index>= repos.size()){
            index=0;
        }
        int hashCode = repos.get(index++).hashCode();
        int  i = Math.abs(hashCode% repos.size());
        System.out.println(repos.get(i));
        return  repos.get(i);
    }

    public static void main(String[] args) {
        LoadBalance hashLoadBalance = new HashLoadBalance();
        ArrayList<String> ipHashes=new ArrayList<>();
        ipHashes.add("192.168.1.1:8081");
        ipHashes.add("192.168.1.2:8081");
        ipHashes.add("192.168.1.3:8081");
        ipHashes.add("192.168.1.2:8081");
        hashLoadBalance.select(ipHashes);
        hashLoadBalance.select(ipHashes);
        hashLoadBalance.select(ipHashes);
        hashLoadBalance.select(ipHashes);


    }
}
